package ynu.edu.elmservlet.framework;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
 * 自定义前端控制器 拦截url格式要求： /控制器类名/控制器方法名
 */
@WebServlet(name = "framework", urlPatterns = "/*")
public class DispatcherServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            
            // 打印请求参数
            System.out.println("Request Parameters:");
            request.getParameterMap().forEach((key, value) -> {
                System.out.println(key + ": " + Arrays.toString(value));
            });
            
            String path = request.getRequestURI().substring(request.getContextPath().length());
            String className = path.substring(1,path.lastIndexOf("/"));
            String methodName = path.substring(path.lastIndexOf("/")+1);
            
            System.out.println("Request path: " + path);
            System.out.println("Class name: " + className);
            System.out.println("Method name: " + methodName);
            
            PrintWriter out = null;
            try {
                Class clazz = Class.forName("ynu.edu.elmservlet.controller."+className);
                Object controller = clazz.newInstance();
                Method method = clazz.getMethod(methodName, new Class[]{HttpServletRequest.class});
                
                Object result = method.invoke(controller, new Object[]{request});
                
                // 处理返回结果
                if (result == null) {
                    response.setStatus(404);
                    result = new HashMap<String, String>() {{
                        put("message", "未找到数据");
                    }};
                } else if (result instanceof Map) {
                    Map<?, ?> resultMap = (Map<?, ?>) result;
                    // 检查是否是错误消息
                    if (resultMap.containsKey("success")) {
                        // 根据 success 字段设置状态码
                        boolean success = (boolean) resultMap.get("success");
                        response.setStatus(success ? 200 : 400);
                    } else if (resultMap.containsKey("message") && !resultMap.containsKey("success")) {
                        // 只有 message 且没有 success 字段时视为错误消息
                        response.setStatus(400);
                    } else {
                        response.setStatus(200);
                    }
                } else {
                    response.setStatus(200);
                }
                
                out = response.getWriter();
                ObjectMapper om = new ObjectMapper();
                out.print(om.writeValueAsString(result));
                
            } catch(Exception e) {
                e.printStackTrace();
                response.setStatus(500);
                Map<String, String> error = new HashMap<>();
                error.put("message", "服务器异常：" + e.getMessage());
                out = response.getWriter();
                ObjectMapper om = new ObjectMapper();
                out.print(om.writeValueAsString(error));
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            response.getWriter().write("{\"message\":\"服务器错误\"}");
        }
    }
}